package com.woniuxy.book87.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.book87.entity.Permission;
import com.woniuxy.book87.mapper.PermissionMapper;
import com.woniuxy.book87.vo.PermissionMenuVo;
import com.woniuxy.book87.vo.PermissionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class PermissionService {

    @Autowired
    PermissionMapper permissionMapper ;
    public List<PermissionMenuVo> findAllMenu(){
        return permissionMapper.selectAllPermisionMenuVo();
    }


    public PageInfo<PermissionVo> findPermissionByPage(Integer now, Integer size, String name) {
        PageHelper.startPage(now,size);
        List<PermissionVo> ps = permissionMapper.selectPermissionByName(name);
        return new PageInfo<>(ps);
    }

    public List<PermissionMenuVo> findAllParentMenu() {
        return permissionMapper.selectAllparentMenu();
    }

    public void add(Permission permission) {
        permission.setInsertTime(new Date());
        permissionMapper.insert(permission);
    }

    public Permission findPermissionByKey(Long id) {
        return permissionMapper.selectByPrimaryKey(id);
    }

    public void edit(Permission permission) {
        Permission permission1 = permissionMapper.selectByPrimaryKey(permission.getId());
        permission.setInsertTime(permission1.getInsertTime());
        permission.setUpdateTime(new Date());
        permissionMapper.updateByPrimaryKey(permission);
    }

    @Transactional
    public void removePermissionByKey(Long id) {
        Permission permission = permissionMapper.selectByPrimaryKey(id);
        if (permission.getParentId() == -1) {
            //这是父菜单   需要删除所有的子菜单
            permissionMapper.deletePermissionByParentId(id);
        }
        permissionMapper.deleteByPrimaryKey(id);
    }
}
